/*******************************************************************************
 * Copyright (c) 2011 EclipseDevX.org and others.
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at:
 * 
 *     http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

package org.eclipsedevx.metrics;

import java.io.IOException;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipsedevx.metrics.model.MetricsData;
import org.eclipsedevx.metrics.model.ProjectHistory;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class DevXMetricsPlugin extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "org.eclipsedevx.metrics";

	private static final QualifiedName METRICS_QN = new QualifiedName(PLUGIN_ID, "metrics");

	// The shared instance
	private static DevXMetricsPlugin plugin;
	
	private ProjectHistory projectHistory;
	
	/**
	 * The constructor
	 */
	public DevXMetricsPlugin() {
		
	}

	public void start(BundleContext context) throws Exception {
		super.start(context);
		
		plugin = this;
	}

	public void stop(BundleContext context) throws Exception {
		plugin = null;
		
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static DevXMetricsPlugin getPlugin() {
		return plugin;
	}
	
	/**
	 * Log the given exception to the Eclipse log.
	 * 
	 * @param t the exception to log
	 */
	public static void logError(Throwable t) {
		getPlugin().getLog().log(
				new Status(IStatus.ERROR, PLUGIN_ID, t.getMessage(), t));
	}
	
	public MetricsData getMetricsData(IResource resource) {
		try {
			String propertyValue = resource.getPersistentProperty(METRICS_QN);
			
			if (propertyValue == null) {
				return null;
			} else {
				return new MetricsData(propertyValue);
			}
		} catch (CoreException e) {
			return null;
		}
	}
	
	public void setMetricsData(IResource resource, MetricsData data) {
		String value = data.toStringToken();
		
		try {
			resource.setPersistentProperty(METRICS_QN, value);
		} catch (CoreException e) {
			
		}
	}
	
	public ProjectHistory getProjectHistory() {
	    if (projectHistory == null) {
	        projectHistory = new ProjectHistory();
	        
	        try {
	        	projectHistory.loadFrom(getStateLocation().append("metrics.history"));
	        } catch (IOException ioe) {
	        	logError(ioe);
	        }
	    }
	    
	    return projectHistory;
	}
	
}
